<template>
  <BasicModal @register="registerModal" @ok="save">
    <div>
      <Select
        :options="role_list"
        :field-names="{ label: 'name', value: 'id' }"
        style="width: 100%"
        placeholder="参考角色"
        showSearch
        @select="referenceRole"
      />
      <BasicTree
        :tree-data="treeData"
        v-model:value="menus"
        checkable
        toolbar
        :checked-keys="checkedKeys"
        title="菜单分配"
      />
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import { useModalInner, BasicModal } from '/@/components/Modal';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { Select } from 'ant-design-vue';
  import { ref } from 'vue';
  import { assignPermission, getPermissionIds, getRoleList } from '/@/api/sys/roles';
  import { transformTreeData } from '/@/utils/helper/transformTreeData';
  import { RoleModel } from '/@/api/sys/model/roleModel';
  const emits = defineEmits(['register', 'success']);
  const treeData = ref<TreeItem[]>();
  const checkedKeys = ref<number[]>([]);
  const menus = ref<number[]>([]);
  const role_id = ref(0);
  const role_list = ref<RoleModel[]>([]);

  function reset() {
    treeData.value = [];
    checkedKeys.value = [];
    menus.value = [];
    role_id.value = 0;
  }

  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    reset();
    setModalProps({ confirmLoading: true });
    let record = data.record;
    role_list.value = await getRoleList(null);
    for (let role of role_list.value) {
      role['label'] = role.name;
      role['value'] = role.id;
    }
    role_id.value = record.id;
    treeData.value = data.data;
    transformTreeData(treeData.value, false, null);
    checkedKeys.value = (await getPermissionIds(record.id)).menus;
    setModalProps({ confirmLoading: false });
  });

  async function referenceRole(id) {
    checkedKeys.value = (await getPermissionIds(id)).menus;
  }

  async function save() {
    setModalProps({ confirmLoading: false });
    await assignPermission(role_id.value, menus.value);
    setModalProps({ confirmLoading: true });
    emits('success');
    closeModal();
  }
</script>

<style scoped></style>
